const Router = require('koa-router');
const router = new Router();
const {db, Op, QueryTypes} = require("../../models/db");
const {xe} = require("../../tools/tool");


router.post('/common/getHistPrice', async ctx => {
    try {
        let tenantId = ctx.user.tenantId
        let body = ctx.request.body
        let transType = xe.toNumber(body.transType)
        let buId = xe.toNumber(body.buId)
        let ids = body.ids
        let beginDate = body.beginDate
        let endDate = body.endDate
        let displayLastPrice = body.displayLastPrice;
        let pageSize = body.pageSize?body.pageSize:50
        let currentPage = body.currentPage?body.currentPage:1
        let offset = (currentPage - 1) *pageSize;
        let sql = `select b.id,a.billDate,d.name buName,b.invName,a.transTypeName,b.spec,b.price,a.billNo 
       from invoice a inner join v_main_info b on a.tenantId=b.tenantId and a.billState='accounted' and a.id=b.iid 
       inner join contact d on a.tenantId=d.tenantId and a.buId=d.id where isnull(b.price,0)<>0 and a.transType=${transType} and a.tenantId=${tenantId} `
        if(buId) {
            sql += ` and a.buId=${buId} `
        }
        if(beginDate) {
            sql += ` and a.bilLDate>='${beginDate}' `
        }
        if(endDate) {
            sql += ` and a.bilLDate<='${endDate}' `
        }
        if(ids.length > 0) {
            sql += ` and b.invId in(${ids.join(',')}) `
        }
        if(displayLastPrice) {
            sql = ` select billDate,buName,invName,transTypeName,spec,price,billNo from (${sql}) a inner join (select max(id) id from (${sql}) a group by invName,transTypeName,spec) b on a.id=b.id  `
        }
        let total = `select count(*) total from (${sql}) a `
        sql += ` order by buName,invName,b.id desc offset ${offset} rows fetch next ${pageSize} rows only; `
        let list = await db.query(sql, {type: QueryTypes.SELECT})
        let t = await db.query(total, {type: QueryTypes.SELECT, plain: true})
        return  ctx.suc('', {
            total: t?t.total:0,
            list
        })
    }
    catch (e) {
        return ctx.err(e)
    }
})






module.exports = router;